package com.leijingqi.aop;

import com.alibaba.fastjson2.JSON;
import com.leijingqi.mapper.OperateLogMapper;
import com.leijingqi.pojo.OperateLog;
import com.leijingqi.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect //标识 不是普通类 是Aop类
//public class TimeAspect {
//    @Pointcut("execution(* com.leijingqi.service.*.*(..)))")
//    private void  pt(){}
//    @Around("pt()") //切入点表达式
//    public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
//        //1  记录开始时间
//        long begin = System.currentTimeMillis();
//        //2  调用原始方法
//        Object result = joinPoint.proceed();
//        //3  记录结束时间  计算耗时
//        long end = System.currentTimeMillis();
//        log.info(joinPoint.getSignature()+"方法执行耗时:{}",end-begin);
//        return result;
//    }
//    @Before("pt()")
//    public void before(JoinPoint joinPoint){
//        //获取目标对象
//        System.out.println(joinPoint.getTarget().getClass().getName()+"???");
//        System.out.println("test_before");
//    }
//}


//操作日志 增删改 用annotation
public class TimeAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.leijingqi.aop.myLog)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取 操作人 id  //获取token
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser =(Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();
        //调用原始方法
        Object result = joinPoint.proceed();
        
        //获取返回值  //对象转换json
        String returnValue = JSON.toJSONString(result);
        //记录耗时
        long costTime = System.currentTimeMillis() - begin;
        //记录操作日志
         OperateLog operateLog =  new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
         operateLogMapper.insert(operateLog);
         log.info("日志对象{}",operateLog);
        return  result;
    }
}